// page/wheat//pages/anchor_budang/anchor_budang.js
var app = getApp();
var util = app.util;
var maiList = app.http.anchor_mailistPost; //接口 排麦列表
var maiType = app.http.maiTypePost; //接口 排麦类型
var maiSubmit = app.http.savePaimaiPost; //接口 提交排麦
var historyJiekou = app.http.historyPost //接口历史记录
var kongkengpaimai = app.http.kongkengpaimaiPost //接口空坑位排


var setmaiOut;  //排麦定时器
var historySetTime; //历史记录

Page({

  /**
   * 页面的初始数据
   */
  data: {
     tab1Index: 0,                 //tab 切换
     is_onshow:1,    // 1调用onshow方法
     mask:0,           //蒙层关闭
     Historylist:[],  //历史记录
     memo:'',    //主播提交备注

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
      let safeAreaBottom = (wx.getSystemInfoSync().screenHeight - wx.getSystemInfoSync().safeArea.bottom) * (750 / wx.getSystemInfoSync().windowWidth)
      this.setData({
        safeAreaBottom
      })
      //计算scrooll的 高度px
      let headHeightpx =  120*wx.getSystemInfoSync().windowWidth/750;
      let maxscrollheight = wx.getSystemInfoSync().windowHeight - headHeightpx
      this.setData({
        maxscrollheight
      })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    //paimai列表
    this.getmaiList();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
     var that =this;
   
    var dangqiInfo = wx.getStorageSync('dangqiInfo')
    if(!dangqiInfo){
      wx.switchTab({
        url: "/page/tabBar/wheat/index"
      })
      return;
    }
    //设置是否是主持
    let isHost = 0;
    if(wx.getStorageSync('dangqiInfo').manager_id == wx.getStorageSync('userinfo').uid){
      isHost = 1
    }
    that.setData({
      isHost
    })

    //页面标题为路由参数
    var beteenTime = dangqiInfo.starttime + " — " + dangqiInfo.endtime
    wx.setNavigationBarTitle({
      title: beteenTime
    })
    this.setData({
      dangqiInfo: dangqiInfo
      , beteenTime
    })
    //paimai列表
    setmaiOut = setInterval(function () {
      this.getmaiList();
    }.bind(this), "3000")
    //paimai类型
    if(this.data.is_onshow){
      this.getmaiType();
    }

    //打卡组件
    var mydaka = this.selectComponent("#my-daka")
    mydaka.showjiekou(); //初始化方法

    //历史接口
    that.history();  
    historySetTime = setInterval(function () {
      this.history();
    }.bind(this), "5000")
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    clearInterval(setmaiOut);
    clearInterval(historySetTime);
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearInterval(setmaiOut);
    clearInterval(historySetTime);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
       console.log("上拉触底事件")
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return util.shareSet(this, "空位排麦中");
  },
  //获取排麦列表
  getmaiList: function () {
    var dangqiInfo = wx.getStorageSync('dangqiInfo')
    var token = wx.getStorageSync('userinfo').token
    var hall_id = wx.getStorageSync('hall_info').id
    maiList({
      token,
      hall_id,
      dangqiid: dangqiInfo.id
    }, false).then(re => {
      //console.log(re);
      if (re.code == 0) {
        var my_uid = wx.getStorageSync('userinfo').uid
        var onList = false //是否是主播
        //获取跳档的个数和补档的个数   相等跳到已排页面
        var tiao = 0;
        var bu = 0;
        for (var i = 0; i < re.data.length; i++) {
          if (re.data[i].tripstop == 1) {
            tiao++;
          }
          if (re.data[i].addin == 1) {
            bu++;
          }
          if (re.data[i].uid == my_uid) {
            onList = true
          }
        }
        


        let isHost = 0
        if (my_uid == re.zhuchi_info.manager_id) {
          isHost = 1
        }


          //当前时间戳
          var curtime = Date.parse( new Date() ).toString();//获取到毫秒的时间戳，精确到毫秒
          curtime = curtime.substr(0,10);//精确到秒
        //档期结束时间
        var endtime = util.riqiTime(dangqiInfo.riqi + " " + dangqiInfo.endtime)
        if (re.data.length == (re.max_num + tiao) ||  new Date().getTime() > endtime || curtime> re.paimaiend) {
          //主播 ，管理员， 主持
          if (isHost || wx.getStorageSync("userinfo").roles.indexOf("1") != -1 || onList){
            wx.redirectTo({
              url: '../main_daka/main_daka',
            })
          }else{
            wx.redirectTo({
              url: '../anchor_yipai/anchor_yipai',
            })
          }
        }
       
        this.setData({
          budangNum: bu,
          tiao: tiao,
          maiList: re.data,
          zhuchi_info: re.zhuchi_info,
          myuid: re.myuid,
          mypaimai: re.mypaimai,
          isHost,
          getpaimaiList:re
        })

      } else {
        console.log("接口返回数据失败", re);
      }
    })
  },


   /*
   * tab 切换
   */
  onTab1Click(event) {
    let index = event.currentTarget.dataset.index;
    this.setData({
      tab1Index: index,
    })
  },
  /*
   *  swipe 切换
   */
  swiperChange(event) {
    this.setData({
      tab1Index: event.detail.current,
    })    
  },
  /*
   *  swipe 切换
   */
  animationfinish(event) {
    this.setData({
      tab1Index: event.detail.current,
    })
  },
  //更换主持人
  updatemainUrl(){
    let userinfo = wx.getStorageSync("userinfo")
    //是主持
    if(this.data.zhuchi_info.manager_id == userinfo.uid){
         
       return;
    }
    
    if (userinfo.roles.indexOf("1") > -1) {
      //小程序管理员
      wx.navigateTo({
        url: "../xcx_chair/xcx_chair"
      });
    } else {
      //主播更换自己
      wx.navigateTo({
        url: "../xcx_chairChange/xcx_chairChange"
      });
    }

  },
  bindmark(){
    this.setData({
      mask:1
    })
  },
  //打卡 福利弹框
  bottomDialog(e){
    var bottomDialog = this.selectComponent("#bottomDialog")
    bottomDialog.setData({
      hideFlag: false,
      selectArray:e.detail.bottomDialogArray,
      title:e.detail.bottomDialogTitle
    })
    bottomDialog.showModal();
  },
  //打卡 福利弹框回调
  bottomDialogIndex(e){
    var mydaka = this.selectComponent("#my-daka")
    mydaka.bottomDialogIndex(e) 
  },
  //打卡 大光弹框
  daguangDialog(e){

    var bottomDialog = this.selectComponent("#daguangDialog")
    bottomDialog.setData({
        show:e.detail.dialogDaguangShow,
        buttons:[{
          text: '取消'
          }, {
              text: '确定',
              extClass: 'daguangSure'
          }] //大光福利弹出框 按钮
    })
  },
  //打卡 大光弹框回调
  daguangSure(e){
    var mydaka = this.selectComponent("#my-daka")
    mydaka.daguangSure(e)
  },
  //打卡 大光弹框输入数字回调
  daguangNumber(e) {
    var mydaka = this.selectComponent("#my-daka")
    mydaka.daguangNumber(e)
  },
  //打卡 受益人
  shouyiren(e){
     this.setData({
      bottomindex:e.detail.bottomindex,
      userindex:e.detail.userindex,
      get_dakadata:e.detail.get_dakadata,
      isedit:e.detail.isedit,
      tid:e.detail.tid,
     })
  },
  //打卡 受益人页面调用的 方法
  addUserdaka(){
    var that = this;
    var mydaka = this.selectComponent("#my-daka")
    //黑麦
    var bottomindex = this.data.bottomindex;
    var dakadatabottomindex = this.data.get_dakadata[bottomindex] //
    if(dakadatabottomindex.type == 4){
      if (that.data.isedit == 0){//新增
        mydaka.setData({
          tid: dakadatabottomindex.benefitlist.id,
        })
      }
    }
    mydaka.setData({
      get_dakadata:that.data.get_dakadata,
      is_onshow: 0     // 不调用onshow 里的方法
    })
    mydaka.addUserdaka()
  },
  //打卡按钮
  showdelet(e){
    this.setData({
      showdelet:e.detail.showdelet
      })
  },
  //打卡
  godaka(){
    var mydaka = this.selectComponent("#my-daka")
    mydaka.godaka()
  },

    //获取排麦类型
    getmaiType: function () {
      var hall_info = wx.getStorageSync('hall_info')
      var token = wx.getStorageSync('userinfo').token
      maiType({
        token,
        hall_id: hall_info.id
      },false).then(re => {
        if (re.code == 0) {
          this.setData({
            maiType: re.data,
            kejiajian: re.kejiajian,
            zishu:re.zishu
          })
        } else {
          console.log("接口返回数据失败", re);
        }
      })
    },
    //加一
    jiayi: function () {
      var hudongpai_index = this.data.hudongpai_index
      this.setData({
        hudongpai_index: hudongpai_index + 1
      })
    },
    //选中类型
    setSueType: function (e) {
      var id = e.currentTarget.dataset.id;
      var index = e.currentTarget.dataset.index;
      this.setData({
        xuanzhong: id,
        xuanzhong_index: index,
        hudongpai_index: 1
      })
    },
    //提交
    submitPaimai: function () {
  
      if (!this.data.xuanzhong) {
        wx.showToast({
          title: '请选择',
          icon: 'none'
        })
        return;
      }
  
      //固定麦位 ：置顶卡和礼物排 顺序 置顶卡优先，礼物排钻数
      var guding_num = this.data.guding_num
      var xuanzhong_index = this.data.xuanzhong_index
      var maiType = this.data.maiType
      var maiList = this.data.maiList
      if (maiType[xuanzhong_index].type == "礼物") {
        var i = 0
        maiList.forEach(function (val, index, arr) {
          if (val["maitype"] == "礼物" || val["maitype"] == "置顶卡") {
            i++
          }
        }, this)
  
        if (guding_num == i) {
          maiList.forEach(function (val, index, arr) {
            if (val["maitype"] == "礼物") {
              if (Number(maiType[xuanzhong_index].num) <= Number(val["num"])) {
                wx.showToast({
                  title: '礼物排已满',
                  icon: 'none'
                })
                return;
              }
            }
          }, this)
        }
      }
      if (maiType[xuanzhong_index].type == "置顶卡") {
        var i = 0
        maiList.forEach(function (val, index, arr) {
          if (val["maitype"] == "置顶卡") {
            i++
          }
        }, this)
        if (guding_num == i) {
          wx.showToast({
            title: '固定麦位已满',
            icon: 'none'
          })
          return;
        }
      }
  
      //置顶卡id
      var card_id = '';
      if (this.data.maiList.length) {
        var maiList = this.data.maiList
        maiList.forEach(function (val, index, arr) {
          if (val["maitype"] == "置顶卡" && val["uid"] == this.data.myuid) {
            card_id = val["card_id"]
          }
        }, this)
      }
  
      this.setData({
        card_id:card_id,
        remark:true
      })

    },
    //取消排麦
    cancelpaimai: function (e) {
      var that = this
      var hall_info = wx.getStorageSync('hall_info')
      var token = wx.getStorageSync('userinfo').token
      var qid = wx.getStorageSync('dangqiInfo').id
      canclepaimai({
        token,
        hall_id: hall_info.id,
        qid
      }).then(re => {
        console.log(re);
        if (re.code == 0) {
          //paimai列表
          that.getmaiList();
          //paimai类型
          that.getmaiType();
          //选中的类型取消
          that.setData({
            xuanzhong: ''
          })
        } else {
          console.log("接口返回数据失败", re);
        }
      })
    },
    //历史接口
    history(){
      var that = this
      var token = wx.getStorageSync('userinfo').token;
      var qid = wx.getStorageSync('dangqiInfo').id
      historyJiekou({
          token,
          qid,
      },false).then(res=>{
            if(res.code == 0){
               that.setData({
                   Historylist:res.data
               })
            }
      })
    },
    //主播排麦弹框 内容
    textareaiInput:function(e){
      let that = this 
      // console.log()
      that.setData({
        memo:e.detail.value==''?'':e.detail.value
      })
    },
    //主播排麦弹框 关闭
    closeMemo:function(){
      let that = this
      this.setData({
        remark:false
      })
    },
    //主播排麦弹框 提交
    submitPaimaiMemo:function(){
            //参数
            var hall_info = wx.getStorageSync('hall_info')
            var token = wx.getStorageSync('userinfo').token
            var qid = wx.getStorageSync('dangqiInfo').id
            var typeid = this.data.xuanzhong
            var nums = this.data.hudongpai_index
            var memo = this.data.memo
            var card_id = this.data.card_id
            var that = this
            kongkengpaimai({
              token,
              hall_id: hall_info.id,
              typeid,
              qid,
              memo,
              nums,
              card_id
            }).then(re => {
              console.log(re);
              that.setData({
                remark: 0
              })
              if (re.code == 0) {
                wx.showToast({
                  title: re.info,
                  icon: 'none',
                  complete: function(){
                    //paimai列表
                    that.getmaiList();
                    //paimai类型
                    that.getmaiType();
                  }
                })
                
                //
                that.setData({
                  xuanzhong: ''
                })
                //
                
              } else if(re.code == -1) {
                wx.showToast({
                  title: re.info,
                  icon: 'none'
                })

              } else {
                console.log("接口返回数据失败", re);
              }
            })
    },
})